package com.swc.wrapper;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.swc.constant.HeaderConstant;
import com.swc.factory.EncryptModeFactory;
import com.swc.property.SecretKeyProperty;
import com.swc.secret.AbstractSecret;
import com.swc.sign.Sha256Sign;
import com.swc.util.JacksonUtil;
import com.swc.util.RsaUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 重新包装http, 解密json请求的内容
 * @author huyupeng
 * @date 2020-09-18
 */
public class DecryptJsonReqParamWrapper extends HttpServletRequestWrapper {

    private Logger logger = LoggerFactory.getLogger(DecryptJsonReqParamWrapper.class);

    private byte[] body;
    private Map<String, String[]> paramMap = new HashMap<>();
    private SecretKeyProperty rsaKeyProperty;
    private AbstractSecret abstractSecret;
    private String secretKey;

    public DecryptJsonReqParamWrapper(HttpServletRequest request, SecretKeyProperty rsaKeyProperty) {
        super(request);
        this.rsaKeyProperty = rsaKeyProperty;

        //由于request并没有提供现成的获取json字符串的方法，所以我们需要将body中的流转为字符串
        if ("post".equalsIgnoreCase(request.getMethod()) || "put".equalsIgnoreCase(request.getMethod())) {
            abstractSecret = new EncryptModeFactory().getEncryptMode(request.getHeader(HeaderConstant.HEADER_ENCRYPT_MODE));
            secretKey = RsaUtil.decrypt(request.getHeader(HeaderConstant.HEADER_SECRET_KEY), rsaKeyProperty.getRsaPrivateKey());
            decryptRequestJsonBody(request);
        }

    }

    /**
     * 对请求体内容进行解密
     * @param request
     * @return
     */
    private void decryptRequestJsonBody(HttpServletRequest request) {
        String jsonStr = getRequestJsonBody(request);
        if (StringUtils.isEmpty(jsonStr)) {
            return;
        }
        Map<String, String> map = null;
        try {
            map = JacksonUtil.json2Map(jsonStr, String.class);
        } catch (Exception e) {
            logger.warn("【网关层返回的数据处理】对请求的JSON数据转MAP失败", e);
            throw new RuntimeException("数据包处理数据失败");
        }
        try {
            TreeMap<String, String> treeMap = new TreeMap<>();
            treeMap.put("request", map.get("request"));
            Sha256Sign sha256Sign = new Sha256Sign(request);
            sha256Sign.dealRequestHeader(treeMap);
            System.out.println(sha256Sign.verifySign(treeMap, secretKey));
            if (!sha256Sign.verifySign(treeMap, secretKey).equals(request.getHeader(HeaderConstant.HEADER_SIGN_KEY))) {
                throw new RuntimeException("验签失败，请检查");
            }
            String bodyStr = abstractSecret.decrypt(map.get("request"), rsaKeyProperty.getRsaPrivateKey(), secretKey);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(bodyStr);
            String data = jsonNode.toString();
            if (StringUtils.isNotEmpty(data)) {
                this.body = data.getBytes();
            }
        } catch (Exception e) {
            logger.warn("【网关层返回的数据处理】对请求的JSON数据解密失败", e);
            throw new RuntimeException("数据包处理数据失败");
        }
    }

    /**
     * 获取请求体内容
     * @param request
     * @return
     */
    public static String getRequestJsonBody(HttpServletRequest request){
        try {
            int contentLength = request.getContentLength();
            if (contentLength < 0) {
                return null;
            }
            byte[] buffer = new byte[contentLength];
            for (int i = 0; i < contentLength;) {

                int readLen = request.getInputStream().read(buffer, i, contentLength - i);
                if (readLen == -1) {
                    break;
                }
                i += readLen;
            }

            String charEncoding = request.getCharacterEncoding();
            if (charEncoding == null) {
                charEncoding = "UTF-8";
            }
            return new String(buffer, charEncoding);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 在使用@RequestBody注解的时候，其实框架是调用了getInputStream()方法，所以我们要重写这个方法
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (body == null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(this.getRequest().getInputStream(), outputStream);
            this.body = outputStream.toByteArray();
        }
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public Object getAttribute(String name) {
        if (paramMap == null || paramMap.get(name) == null) {
            return null;
        }
        return paramMap.get(name)[0];
    }

    @Override
    public String getParameter(String name) {
        if (paramMap == null || paramMap.get(name) == null) {
            return null;
        }
        return paramMap.get(name)[0];
    }

    @Override
    public String[] getParameterValues(String name) {
        if (paramMap == null) {
            return null;
        }
        return paramMap.get(name);
    }

    /**
     * 不重写该方法的话，第二次请求会报400错误
     * @return
     */
    @Override
    public long getContentLengthLong() {
        return body.length;
    }

}
